package com.qilu.pe.ui.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qilu.pe.R;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Config;
import com.qilu.pe.base.Global;
import com.qilu.pe.dao.bean.CategoryItem;
import com.qilu.pe.dao.bean.PriceRangeOption;
import com.qilu.pe.dao.bean.Product;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.AlertUtil;
import com.qilu.pe.support.util.GlideUtil;
import com.qilu.pe.support.util.Logg;
import com.qilu.pe.ui.activity.GenProductOrderActivity;
import com.qilu.pe.ui.activity.ProDetailActivity;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.BaseFragment;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.util.BarUtils;
import com.ruitu.arad.util.SizeUtils;
import com.ruitu.arad.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.w3c.dom.Text;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

// 商城
public class Home4Fragment extends BaseFragment implements View.OnClickListener {
    private RecyclerView rcv_list;// 商城商品列表

    private ProListAdapter adapter;
    private List<Product> productList = new ArrayList<>();

    private Product currPro;// 当前操作的商品

    public Home4Fragment() {

    }

    public static Home4Fragment newInstance() {
        Home4Fragment fragment = new Home4Fragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        adapter = new ProListAdapter(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_home4, container, false);
        rcv_list = v.findViewById(R.id.rcv_list);
        v.findViewById(R.id.vFilter).setOnClickListener(this);

        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        rcv_list.setLayoutManager(manager);
        rcv_list.setAdapter(adapter);

        setListeners();

        reqProductList();
        reqPriceList();

        alert = new AlertDialog.Builder(getActivity(), R.style.Dialog_FS).create();
        mCategoryDialog = new AlertDialog.Builder(getActivity(), R.style.Dialog_FS).create();
        return v;
    }

    private void setListeners() {
        adapter.setOnItemClickListener(new ListBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("id", productList.get(position).getId());
                startActivity(ProDetailActivity.class, bundle);
            }
        });
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.vFilter:
                if (mCategoryItems.isEmpty()) {
                    reqPriceList();
                    reqCategoryList(true);
                } else {
                    showCategoryDialog();
                }
                break;
        }
    }

    // 获取商品列表
    private Disposable reqProductList() {
        return APIRetrofit.getDefault().reqProductList(1, 999999, "", mPriceRange, mCategoryId)
                .compose(RxUtil.<BaseResult2<List<Product>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<Product>>>() {
                    @Override
                    public void accept(BaseResult2<List<Product>> listResult2) throws Exception {
                        hideProgress();
                        productList = listResult2.getData();
                        adapter.setDataList(productList);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private AlertDialog alert;// 弹窗
    private View alert_view;
    private int num = 1;// 记录输入的商品数量

    public void showDialog() {// 弹窗界面
        alert.show();
        alert_view = View.inflate(getActivity(), R.layout.layout_alert_buy_product, null);

        final TextView tv_num = alert_view.findViewById(R.id.tv_num);
        final TextView tv_minus = alert_view.findViewById(R.id.tv_minus);
        final TextView tv_plus = alert_view.findViewById(R.id.tv_plus);
        View vTest=alert_view.findViewById(R.id.v_test);
        RoundedImageView iv_product = alert_view.findViewById(R.id.iv_product);
        GlideUtil.loadImg(Config.URL_IMG + currPro.getPicture(), iv_product);
        vTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert.dismiss();
            }
        });
        tv_num.setText("" + num);

        tv_minus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num = Integer.parseInt(tv_num.getText().toString().trim());
                num -= 1;
                if (num <= 1) {
                    num = 1;
                }
                tv_num.setText("" + num);
            }
        });
        tv_plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num = Integer.parseInt(tv_num.getText().toString().trim());
                num += 1;
                tv_num.setText("" + num);
            }
        });

        alert_view.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert.dismiss();
                Bundle bundle = new Bundle();
                bundle.putSerializable("product", currPro);
                bundle.putString("num", num + "");
                startActivity(GenProductOrderActivity.class, bundle);
            }
        });

        AlertUtil.setAlertBottomInStyle(alert.getWindow(), alert_view, getActivity());
    }

    private class ProListAdapter extends ListBaseAdapter<Product> {

        public ProListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_product_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, final int position) {
            CardView cv_item = holder.getView(R.id.cv_item);
            RoundedImageView iv_pro_pic = holder.getView(R.id.iv_pro_pic);
            TextView tv_name = holder.getView(R.id.tv_name);
            TextView tv_intro = holder.getView(R.id.tv_intro);
            TextView tv_price = holder.getView(R.id.tv_price);
            TextView tv_buy = holder.getView(R.id.tv_buy);

            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) cv_item.getLayoutParams();
            if (position == 0) {
                params.topMargin = SizeUtils.dp2px(12);
                params.bottomMargin = SizeUtils.dp2px(6);
            } else if (position == mDataList.size() - 1) {
                params.topMargin = SizeUtils.dp2px(6);
                params.bottomMargin = SizeUtils.dp2px(12);
            } else {
                params.topMargin = SizeUtils.dp2px(6);
                params.bottomMargin = SizeUtils.dp2px(6);
            }

            Product product = mDataList.get(position);
            tv_name.setText(product.getName());
            tv_intro.setText(product.getIntro());
            tv_price.setText("¥" + product.getPrice());
            GlideUtil.loadImg(Config.URL_IMG + product.getPicture(), iv_pro_pic);

            tv_buy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    currPro = productList.get(position);
                    showDialog();
                }
            });
        }
    }

    private AlertDialog mCategoryDialog;
    private View mDialogView;
    private List<CategoryItem> mCategoryItems = new ArrayList<>();
    private String mPriceRange = "";
    private String mCategoryId = "";
    private List<PriceRangeOption> mPriceRangeOptions = new ArrayList<>();

    public void showCategoryDialog() {
        mCategoryDialog.show();
        if (mDialogView == null) {
            mDialogView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_category_filter, null, false);
            mDialogView.findViewById(R.id.vContainer).setPadding(0, BarUtils.getStatusBarHeight(getContext()), 0, 0);
            mDialogView.findViewById(R.id.v_dismiss).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mCategoryDialog.dismiss();
                }
            });
            RecyclerView priceRecycler = mDialogView.findViewById(R.id.vPriceRecycler);
            GridLayoutManager manager = new GridLayoutManager(getActivity(), 3);
            priceRecycler.setLayoutManager(manager);
            PriceRangeAdapter priceAdapter = new PriceRangeAdapter(R.layout.item_category_item, mPriceRangeOptions);
            priceRecycler.setAdapter(priceAdapter);

            RecyclerView recycler = mDialogView.findViewById(R.id.vRecycler);
            GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 3);
            recycler.setLayoutManager(layoutManager);
            CategoryAdapter adapter = new CategoryAdapter(R.layout.item_category_item, mCategoryItems);
            recycler.setAdapter(adapter);

            mCategoryDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    showProgress();
                    reqProductList();
                }
            });
        }
        AlertUtil.setAlertRightInStyleNoDim(mCategoryDialog.getWindow(), mDialogView, getActivity());
    }

    public void reqCategoryList(final boolean showDialog) {
        showProgress();
        APIRetrofit.getDefault().getShopCategory(Global.HEADER)
                .compose(RxUtil.<BaseResult2<List<CategoryItem>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<CategoryItem>>>() {
                    @Override
                    public void accept(BaseResult2<List<CategoryItem>> res) throws Exception {
                        hideProgress();
                        if (res.isSuccess()) {
                            mCategoryItems.addAll(res.getData());
                            if (showDialog) {
                                showCategoryDialog();
                            }
                        } else {
                            ToastUtils.showShort(res.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    public class CategoryAdapter extends BaseQuickAdapter<CategoryItem, BaseViewHolder> {

        private CategoryItem mPreSelected;

        public CategoryAdapter(int layoutResId, List<CategoryItem> data) {
            super(layoutResId, data);
        }

        public CategoryAdapter(int layoutResId) {
            super(layoutResId);
        }

        @Override
        protected void convert(BaseViewHolder holder, final CategoryItem item) {
            TextView option = holder.itemView.findViewById(R.id.vOption);
            option.setText(item.getName());
            option.setSelected(item.isSlected());

            option.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mPreSelected != null) {
                        mPreSelected.setSlected(false);
                    }
                    item.setSlected(true);
                    mCategoryId = String.valueOf(item.getId());
                    mPreSelected = item;
                    notifyDataSetChanged();
                }
            });
        }
    }

    public void reqPriceList() {
        APIRetrofit.getDefault().getPriceRange(Global.HEADER)
                .compose(RxUtil.<BaseResult2<List<PriceRangeOption>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<PriceRangeOption>>>() {
                    @Override
                    public void accept(BaseResult2<List<PriceRangeOption>> res) throws Exception {
                        if (res.isSuccess()) {
                            mPriceRangeOptions = res.getData();
                        } else {
                            ToastUtils.showShort(res.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });
    }

    public class PriceRangeAdapter extends BaseQuickAdapter<PriceRangeOption, BaseViewHolder> {

        private PriceRangeOption mPreSelected;

        public PriceRangeAdapter(int layoutResId, List<PriceRangeOption> data) {
            super(layoutResId, data);
        }

        public PriceRangeAdapter(int layoutResId) {
            super(layoutResId);
        }

        @Override
        protected void convert(BaseViewHolder holder, final PriceRangeOption item) {
            TextView option = holder.itemView.findViewById(R.id.vOption);
            option.setText(item.getName());
            option.setSelected(item.isSelected());

            option.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mPreSelected != null) {
                        mPreSelected.setSelected(false);
                    }
                    item.setSelected(true);
                    mPriceRange = String.valueOf(item.getId());
                    mPreSelected = item;
                    notifyDataSetChanged();
                }
            });
        }
    }
}